from flask import Flask, request, redirect, url_for

app = Flask(__name__)

# 模拟用户数据库
users = {
    "user1": "password1",
    "user2": "password2"
}

# 模拟会话
sessions = {}


# 网关
@app.before_request
def gateway():
    # 检查是否有会话
    session_id = request.cookies.get('session_id')
    if session_id not in sessions and request.endpoint != 'login':
        return redirect(url_for('login'))


# 用户登录拦截器
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if username in users and users[username] == password:
            # 创建会话
            session_id = username
            sessions[session_id] = username
            response = redirect(url_for('index'))
            response.set_cookie('session_id', session_id)
            return response
        else:
            return "登录失败", 401
    return '''
        <form method="post">
            用户名: <input type="text" name="username"><br>
            密码: <input type="password" name="password"><br>
            <input type="submit" value="登录">
        </form>
    '''


@app.route('/')
def index():
    return "欢迎来到首页!"


@app.route('/logout')
def logout():
    session_id = request.cookies.get('session_id')
    if session_id in sessions:
        del sessions[session_id]
    response = redirect(url_for('login'))
    response.delete_cookie('session_id')
    return response


if __name__ == '__main__':
    app.run(debug=True)
